#include <math.h>    // fabs()
#include <float.h>   // DBL_MAX
#include <string.h>  // memcpy() strncpy()
#include <stdlib.h>  // malloc()
#include <sys/wait.h>

#include "rcs.hh"  // RCS_CMD_CHANNEL, etc.
#include "rcs_print.hh"
#include "timer.hh"         // esleep, etc.
#include "nml_intf/zuc.hh"  // ZUC NML
#include "nml_intf/zuc_nml.hh"
#include "nml_intf/zucglb.h"  // ZUC_INIFILE

#include "inifile.hh"
#include "errcode.h"

// static const char *instance_name = "task_instance";

// if using a Python-based HAL module in task, normal HAL_FILE's are run too early.
// execute those here if specified via POSTTASK_HALFILE in ini ,
int zucRunHalFiles(const char* filename)
{
    IniFile inifile;
    const char* inistring;
    int lineno, status;
    int n = 1;
    pid_t pid;

    if (inifile.Open(filename) == false)
    {
        return -1;
    }
    while (NULL != (inistring = inifile.Find("POSTTASK_HALFILE", "HAL", n, &lineno)))
    {
        if ((pid = vfork()) < 0)
            perror("vfork()");
        else if (pid == 0)
        {
            execlp("halcmd", "halcmd", "-i", filename, "-f", inistring, NULL);
            // perror("execlp halcmd");
        }
        else
        {
            if ((waitpid(pid, &status, 0) == pid) && WEXITSTATUS(status))
                rcs_print("'halcmd -i %s -f %s' exited with  %d\n", filename, inistring, WEXITSTATUS(status));
        }
        n++;
    }
    return 0;
}

extern "C" void initzuctask();
extern "C" void initinterpreter();
extern "C" void initzuccanon();
